import { AppServiceUtility } from "src/projects/app/appService";
import { addon, Permission } from "pao-aop";
import { reactControl, ReactViewControl, ReactViewState, ReactView } from "pao-aop-client";
import { MainContent } from "src/business/components/style-components/main-content";
import { isPermission } from "src/projects/app/permission";
import React from "react";
import Form from "antd/lib/form/Form";
// import { ROUTE_PATH } from "src/projects/router";
import { request } from "src/business/util_tool";
import { Select, Row, Button, Col, Input, DatePicker, Checkbox, message } from 'antd';
// import { ROUTE_PATH } from "src/projects/router";
import { MainCard } from "src/business/components/style-components/main-card";
import TextArea from "antd/lib/input/TextArea";
import moment from 'moment';
import { checkMin1, checkPhone } from "./validate";
/**
 * 状态：活动室预约页面
 */
export interface ChangeActivityRoomReservationViewState extends ReactViewState {
    // 活动室列表
    room_list: any;
    // 详情
    data_info?: any;
    // 选择的活动室
    select_room?: any;
}
/**
 * 组件：活动室预约页面视图
 */
export class ChangeActivityRoomReservationView extends ReactView<ChangeActivityRoomReservationViewControl, ChangeActivityRoomReservationViewState> {
    constructor(props: ChangeActivityRoomReservationViewControl) {
        super(props);
        this.state = {
            room_list: [],
            data_info: [],
            select_room: [],
        };
    }
    componentDidMount() {
        // 活动室详情
        request(this, AppServiceUtility.activity_service.get_activity_room_list!({}, 1, 99))
            .then((datas: any) => {
                this.setState({
                    room_list: datas.result ? datas.result : [],
                });
            });
        if (this.props.match!.params.key) {
            // 活动室预约详情
            request(this, AppServiceUtility.activity_service.get_activity_room_reservation_list_all!({ id: this.props.match!.params.key }, 1, 1))
                .then((datas: any) => {
                    this.setState(
                        {
                            data_info: datas.result && datas.result[0] ? datas.result[0] : [],
                        },
                        () => {
                            this.roomChange(datas.result[0]['reservate_room_id']);
                        }
                    );
                });
        }
    }
    backList() {
        history.back();
    }
    roomChange(e: any) {
        let select_room: any = [];
        this.state.room_list.forEach((item: any, index: number) => {
            if (item.id === e) {
                select_room = item;
            }
        });
        this.props.form.setFieldsValue({
            reservate_device: ''
        });
        setTimeout(
            () => {
                this.setState({
                    select_room,
                });
            },
            100
        );
    }
    handleSubmit = (e: any) => {
        e.preventDefault();
        const { form } = this.props;
        form!.validateFields((err: Error, values: any) => {
            if (!err) {
                // 补全ID主键
                if (this.props.match!.params.key) {
                    values['id'] = this.props.match!.params.key;
                }
                // 补充预约日期
                values['reservate_datestr'] = values['reservate_date'].format('YYYY-MM-DD');
                // return;
                request(this, AppServiceUtility.activity_service.update_activity_room_reservation!(values))
                    .then((datas: any) => {
                        if (datas === 'Success') {
                            message.info('预约成功');
                            this.props.history!.goBack();
                        } else {
                            message.error(datas);
                        }
                    })
                    .catch((error: any) => {
                        message.error(error);
                    });
            }
        });
    }
    format(num: number = 0) {
        var myDate = num === 0 ? new Date() : new Date(new Date().getTime() + 24 * 60 * 60 * num * 1000);
        let Y: any = myDate.getFullYear() + '-';
        let M: any = (myDate.getMonth() + 1 < 10 ? '0' + (myDate.getMonth() + 1) : myDate.getMonth() + 1) + '-';
        let D: any = myDate.getDate() + ' ';
        return Y + M + D;
    }
    disabledDate(current: any) {
        const select_room = this.state.select_room;
        if (current) {
            if (select_room.hasOwnProperty('reservate_info')) {
                const now_date: any = current['_d'];
                const date_str: string = `${now_date.getFullYear()}-${(now_date.getMonth() + 1).toString().padStart(2, '0')}-${now_date.getDate().toString().padStart(2, '0')}`;
                for (let i in select_room['reservate_info']) {
                    if (select_room['reservate_info'][i]) {
                        if (select_room['reservate_info'][i].hasOwnProperty('reservate_datestr') && select_room['reservate_info'][i]['reservate_datestr'] === date_str) {
                            return true;
                        }
                    }
                }
            }
            if (select_room.hasOwnProperty('end_date') && select_room['end_date'] !== '') {
                return current > moment(select_room['end_date'], 'YYYY-MM-DD').add(1, 'days') || current < moment().endOf('day');
            }
        }
        return current && current < moment().endOf('day');
    }
    render() {
        const redeirect = isPermission(this.props.permission!);
        if (redeirect) {
            return redeirect;
        }
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        };
        const { getFieldDecorator } = this.props.form!;
        let { data_info, room_list, select_room } = this.state;
        // 超过时间或者查看的不允许编辑

        // 预约当前的时间戳
        let resDateTimestamp = new Date(data_info['reservate_datestr'] + ' 00:00:00').getTime();
        let nowDateTimestamp = new Date().getTime();
        let isDisabled: boolean = false;
        if (nowDateTimestamp > resDateTimestamp) {
            isDisabled = true;
        }
        return (
            <MainContent>
                <Form {...formItemLayout} onSubmit={this.handleSubmit}>
                    <MainCard title='活动室预约'>
                        <Row type="flex" justify="center">
                            <Col span={12}>
                                <Form.Item label='选择活动室'>
                                    {getFieldDecorator('reservate_room_id', {
                                        initialValue: data_info['reservate_room_id'] ? data_info['reservate_room_id'] : '',
                                        rules: [{
                                            required: true,
                                            message: '请选择活动室'
                                        }],
                                    })(
                                        <Select disabled={isDisabled} placeholder="请选择活动室" onChange={(e: any) => this.roomChange(e)}>
                                            {room_list!.map((item: any, index: any) => {
                                                return <Select.Option key={index} value={item['id']}>{item['activity_room_name']}</Select.Option>;
                                            })}
                                        </Select>
                                    )}
                                </Form.Item>
                                {
                                    !select_room.hasOwnProperty('id') ?
                                        <Form.Item label='活动室设备'>
                                            <div>请先选择要预约的活动室</div>
                                        </Form.Item> :
                                        <Form.Item label='活动室设备'>
                                            {getFieldDecorator('reservate_device', {
                                                initialValue: data_info.hasOwnProperty('reservate_device') ? data_info['reservate_device'] : (select_room.hasOwnProperty('device_list') && select_room['device_list'].length > 0 ? select_room['device_list'] : []),
                                                rules: [{
                                                    required: false,
                                                    message: '请选择要预约的活动室设备'
                                                }],
                                            })(
                                                select_room['device_list'] && select_room['device_list'].length === 0 ? <div>该活动室下没有可预约设备</div> : <Checkbox.Group
                                                    disabled={isDisabled}
                                                    options={select_room['device_list'].map((item: any, index: any) => {
                                                        return { label: item['device_name'], value: item['device_name'] };
                                                    })}
                                                />
                                            )}
                                        </Form.Item>
                                }
                                {
                                    !select_room.hasOwnProperty('id') ? null :
                                        <Form.Item label='活动室开放时间'>
                                            <div>{select_room['begin_date'] && select_room['end_date'] ? `${select_room['begin_date']} - ${select_room['end_date']}` : '暂无开放时间'}</div>
                                        </Form.Item>
                                }
                                {!select_room.hasOwnProperty('id') ? <Form.Item label='选择预约日期'>
                                    <div>请先选择要预约的活动室</div>
                                </Form.Item> :
                                    <Form.Item label='选择预约日期'>
                                        {getFieldDecorator('reservate_date', {
                                            initialValue: data_info['reservate_date'] ? moment(data_info['reservate_date'], 'YYYY-MM-DD') : '',
                                            // moment(this.format(), 'YYYY-MM-DD')
                                            rules: [{
                                                required: true,
                                                message: '请选择预约日期'
                                            }],
                                        })(
                                            <DatePicker placeholder="请选择预约日期" disabledDate={(e) => this.disabledDate(e)} format="YYYY-MM-DD" disabled={isDisabled} />
                                        )}
                                    </Form.Item>}
                                <Form.Item label='预约人数'>
                                    {getFieldDecorator('reservate_quantity', {
                                        initialValue: data_info['reservate_quantity'] ? data_info['reservate_quantity'] : '',
                                        rules: [{
                                            required: true,
                                            validator: (_: any, value: any, cb: any) => {
                                                if (select_room.hasOwnProperty('max_quantity') && Number(value) > select_room['max_quantity']) {
                                                    cb(`活动室最大容纳人数：${select_room['max_quantity']}`);
                                                    return;
                                                }
                                                checkMin1(_, value, cb, '预约人数');
                                            }
                                        }],
                                    })(
                                        <Input disabled={isDisabled} autoComplete='off' placeholder={select_room.hasOwnProperty('max_quantity') && select_room['max_quantity'] ? `最大可预约${select_room['max_quantity']}人` : '请输入预约人数'} />
                                    )}
                                </Form.Item>
                                <Form.Item label='联系人'>
                                    {getFieldDecorator('contacts', {
                                        initialValue: data_info['contacts'] ? data_info['contacts'] : '',
                                        rules: [{
                                            required: true,
                                            message: '请输入联系人'
                                        }],
                                    })(
                                        <Input disabled={isDisabled} autoComplete='off' placeholder="请输入联系人" />
                                    )}
                                </Form.Item>
                                <Form.Item label='联系方式'>
                                    {getFieldDecorator('phone', {
                                        initialValue: data_info['phone'] ? data_info['phone'] : '',
                                        rules: [{
                                            required: true,
                                            validator: (_: any, value: any, cb: any) => checkPhone(_, value, cb, '联系方式')
                                        }],
                                    })(
                                        <Input disabled={isDisabled} autoComplete='off' placeholder="请输入联系方式" />
                                    )}
                                </Form.Item>
                                <Form.Item label='备注'>
                                    {getFieldDecorator('remarks', {
                                        initialValue: data_info['remarks'] ? data_info['remarks'] : '',
                                    })(
                                        <TextArea disabled={isDisabled} />
                                    )}
                                </Form.Item>
                            </Col>
                        </Row>
                    </MainCard>
                    <MainCard>
                        <Row type="flex" justify="center" className="ctrl-btns">
                            <Button disabled={isDisabled} htmlType='submit' type='primary'>保存</Button>
                            <Button type='ghost' name='返回' htmlType='button' onClick={this.backList}>返回</Button>
                        </Row>
                    </MainCard>
                </Form>
            </MainContent>
        );
    }
}

/**
 * 控件：活动室预约页面控件
 * @description 活动室预约页面控件
 * @author
 */
@addon('ChangeActivityRoomReservationViewControl', '活动室预约页面控件', '活动室预约页面控件')
@reactControl(Form.create<any>()(ChangeActivityRoomReservationView), true)
export class ChangeActivityRoomReservationViewControl extends ReactViewControl {
    /** 视图权限 */
    public permission?: Permission;
}